package net.tensor.tensor.client.server.web;

import net.tensor.tensor.client.server.service.TokenService;
import net.tensor.tensor.client.server.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;

/**
 * 页面控制器，本示例中所有controller都在这里
 *
 * @author Q
 */
@Controller
public class MainPageController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 主页
     */
    @GetMapping(value = {"/", "/index"})
    public String index() {
        return "index";
    }

    /**
     * 回调
     */
    @GetMapping("/callback")
    public ModelAndView callback(@RequestParam("code") String code) throws UnsupportedEncodingException {
        String token = tokenService.getToken(code);
        if (StringUtils.isNotBlank(token)) {
            redisUtil.set("mytoken", token);
            return new ModelAndView("redirect:/user-info");
        }
        throw new RuntimeException("请求超时");
    }

    /**
     * 用于测试获取token与访问资源服务器资源的功能
     */
    @GetMapping("/user-info")
    public ModelAndView userInfoPage() {
        String token = null;
        try {
            token = redisUtil.get("mytoken").toString();
        } catch (Exception ignored) {
        }
        ModelAndView modelAndView = new ModelAndView("user-info");
        //尝试获取资源
        tokenService.tryGetUserInfo(modelAndView, token);
        return modelAndView;
    }

}
